package com.smart.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.smart.constants.SmartConstants;
import com.smart.dao.DeliveryDAO;
import com.smart.dao.UserDAO;
import com.smart.model.AccessToken;
import com.smart.model.Admin;
import com.smart.model.Delivery;
import com.smart.model.template.NewDeliveryData;
import com.smart.model.template.NewDeliveryTemplate;
import com.smart.model.template.Parameter;
import com.smart.model.template.RcvDeliveryData;
import com.smart.model.template.RcvDeliveryTemplate;
import com.smart.service.DeliveryService;
import com.smart.util.JPushUtil;
import com.smart.util.WeixinUtil;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;

@RestController
public class DeliveryController {
	@RequestMapping(value = "/users/{id}/deliverys", method = RequestMethod.GET)
	@ResponseBody
	public List<Delivery> getDeliveryList(@PathVariable("id") int userID, @RequestParam("phone") String phone,
			@RequestParam("status") int status, @RequestParam("page") int page,
			@RequestParam("pagesize") int pageSize) {
		DeliveryService deliveryService = new DeliveryService();
		List<Delivery> list = null;
		System.out.println("userID == " + userID);
		System.out.println("phone == " + phone);
		try {
			list = deliveryService.getDeliveryList(phone, status, page, pageSize);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@RequestMapping(value = "/pc/get_all_deliverys", method = RequestMethod.POST)
	public void getAllDeliverys(HttpServletRequest req, HttpServletResponse resp) {
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = 10;
		DeliveryDAO deliveryDAO = new DeliveryDAO();
		List<Delivery> deliveryList = new ArrayList<Delivery>();
		try {
			deliveryList = deliveryDAO.getDeliveryInPage(page, pageSize);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JSONArray deliveryArray = new JSONArray();
		for (Delivery d : deliveryList) {
			JSONObject jsonObject = JSONObject.fromObject(d);
			deliveryArray.add(jsonObject);
		}
		int count = 0;
		try {
			count = deliveryDAO.getCount();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("count", count);
		jsonObject.put("content", deliveryList);
		System.out.println(jsonObject);
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = resp.getWriter();
			out.print(jsonObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value="/pc/delivery", method = RequestMethod.POST)
    public void dealNewDelivery(HttpServletRequest req, HttpServletResponse resp) {
    	boolean success=false;
    	Date date = new Date();
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Delivery delivery = new Delivery();
    	Admin adminInfo = (Admin) req.getSession().getAttribute("admin");
    	delivery.setCommunityId(adminInfo.getCommunityId());
    	delivery.setTelephoneNum(req.getParameter("telephoneNum"));
    	delivery.setUserName(req.getParameter("name"));
    	delivery.setDeliveryCom(req.getParameter("company"));
    	delivery.setOrderNum(req.getParameter("number"));
    	delivery.setExtraInfo(req.getParameter("other"));
    	delivery.setDate(format.format(date));
    	delivery.setStatus(0);
    	
    	DeliveryDAO deliveryDAO = new DeliveryDAO();
    	PrintWriter out=null;
    	try {
			deliveryDAO.addDelivery(delivery);
			this.informNewDelivery(delivery);
			@SuppressWarnings("deprecation")
			JPushClient jpushClient = new JPushClient(SmartConstants.JPUSH_MASTER_SECRET, 
					SmartConstants.JPUSH_APPKEY, 3);
			PushResult result = jpushClient.sendPush(JPushUtil.
					buildPushObject_all_alias_notice(delivery.getTelephoneNum(), "您有新的快递"));
			System.out.println(result);
			success=true;
			out= resp.getWriter();
			out.print(success);
			out.flush();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Connection error, should retry later");
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Should review the error, and fix the request");
			System.out.println("HTTP Status: " + e.getStatus());
			System.out.println("Error Code: " + e.getErrorCode());
			System.out.println("Error Message: " + e.getErrorMessage());
		}
    }

	public void informNewDelivery(Delivery delivery) throws SQLException {

		UserDAO userDAO = new UserDAO();
		String openId = userDAO.getOpenIdByTel(delivery.getTelephoneNum());
		if (openId == null || openId.isEmpty()) {
			System.out.println("no user");
			return;
		}
		Parameter first = new Parameter();
		Parameter name = new Parameter();
		Parameter deliveryCom = new Parameter();
		Parameter orderNum = new Parameter();
		Parameter remark = new Parameter();
		first.setValue("");
		name.setValue(delivery.getUserName());
		deliveryCom.setValue(delivery.getDeliveryCom());
		orderNum.setValue(delivery.getOrderNum());
		remark.setValue(delivery.getExtraInfo());
		NewDeliveryData newDeliveryData = new NewDeliveryData();
		newDeliveryData.setKuaidiname(deliveryCom);
		newDeliveryData.setFirst(first);
		newDeliveryData.setName(name);
		newDeliveryData.setNum(orderNum);
		newDeliveryData.setRemark(remark);
		NewDeliveryTemplate newDeliveryTemplate = new NewDeliveryTemplate();
		newDeliveryTemplate.setData(newDeliveryData);
		newDeliveryTemplate.setTemplate_id("8Kjoy-bH-rSjvEul8lASuBMiZEMRtGKkwQSgPMBFPiw");
		newDeliveryTemplate.setTouser(openId);
		AccessToken token = WeixinUtil.getAccessToken();
		String message = JSONObject.fromObject(newDeliveryTemplate).toString();
		System.out.println(message);
		WeixinUtil.sendTemplateMessage(token, message);
		return;

	}

	@RequestMapping(value = "/pc/search_delivery", method = RequestMethod.POST)
	public void searchDelivery(HttpServletRequest req, HttpServletResponse resp) {
		String telephoneNum = req.getParameter("phone");
		String timeFrom = req.getParameter("timeFrom");
		String timeTo = req.getParameter("timeTo");
		int status = -1;
		String stat = req.getParameter("status");
		if (!stat.isEmpty())
			status = Integer.parseInt(stat);
		DeliveryDAO deliveryDAO = new DeliveryDAO();
		List<Delivery> deliveryList = new ArrayList<Delivery>();
		try {
			deliveryList = deliveryDAO.searchDelivery(telephoneNum, timeFrom, timeTo, status);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int count = 0;
		count = deliveryList.size();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("count", count);
		jsonObject.put("content", deliveryList);
		System.out.println(jsonObject);
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = resp.getWriter();
			out.print(jsonObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/pc/recive_delivery", method = RequestMethod.POST)
	public void reciveDelivery(HttpServletRequest req, HttpServletResponse resp) {
		int id = Integer.parseInt(req.getParameter("id"));
		int status = Integer.parseInt(req.getParameter("status"));
		DeliveryDAO deliveryDAO = new DeliveryDAO();
		boolean success = false;
		Delivery delivery = new Delivery();
		try {
			deliveryDAO.updateDeliveryStatById(id, status);
			success = true;
			delivery = deliveryDAO.getDeliveryById(id);
			informRcvDelivery(delivery);
			@SuppressWarnings("deprecation")
			JPushClient jpushClient = new JPushClient(SmartConstants.JPUSH_MASTER_SECRET, 
					SmartConstants.JPUSH_APPKEY, 3);
			PushResult result = jpushClient.sendPush(JPushUtil.
					buildPushObject_all_alias_notice(delivery.getTelephoneNum(), "快递已签收"));
			System.out.println(result);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PrintWriter out = null;
		try {
			out = resp.getWriter();
			out.print(success);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.flush();
			out.close();
		}
	}

	public void informRcvDelivery(Delivery delivery) throws SQLException {

		UserDAO userDAO = new UserDAO();
		String openId = userDAO.getOpenIdByTel(delivery.getTelephoneNum());
		if (openId == null || openId.isEmpty()) {
			System.out.println("no user");
			return;
		}

		Parameter first = new Parameter();
		Parameter keyword1 = new Parameter();
		Parameter keyword2 = new Parameter();
		Parameter keyword3 = new Parameter();
		Parameter remark = new Parameter();
		first.setValue("亲爱的业主，您好，您已成功领取快递1份");
		keyword1.setValue(delivery.getUserName());
		keyword2.setValue(delivery.getOrderNum());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
		String dateTime = sdf.format(date);
		keyword3.setValue(dateTime);
		remark.setValue(delivery.getExtraInfo());
		RcvDeliveryData rcvDeliveryData = new RcvDeliveryData();
		rcvDeliveryData.setFirst(first);
		rcvDeliveryData.setKeyword1(keyword1);
		rcvDeliveryData.setKeyword2(keyword2);
		rcvDeliveryData.setKeyword3(keyword3);
		rcvDeliveryData.setRemark(remark);
		RcvDeliveryTemplate rcvDeliveryTemplate = new RcvDeliveryTemplate();
		rcvDeliveryTemplate.setData(rcvDeliveryData);
		rcvDeliveryTemplate.setTemplate_id("GZSO5PdCPYitekf9GkhERD0AfEb_stN4-vKFpMmQNs0");
		rcvDeliveryTemplate.setTouser(openId);
		AccessToken token = WeixinUtil.getAccessToken();
		String message = JSONObject.fromObject(rcvDeliveryTemplate).toString();
		System.out.println(message);
		WeixinUtil.sendTemplateMessage(token, message);
		return;
	}
}
